﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using MyWindowsMediaPlayer_V2;
using System.Collections.Specialized;
using System.Windows.Forms;
using System.Windows.Controls.Primitives;

namespace WpfApplication
{
    public partial class MainWindow : Window
    {
        public static System.Windows.Controls.MediaElement mediaInstance { get; private set; }
        private bool isUserMovingSlider = false;
        private Playlist playlist;
        private Bibliotheque bibliotheque;

        public MainWindow()
        {
            InitializeComponent();
            mediaInstance = mediaElement;
            playlist = new Playlist(mediaInstance);
            bibliotheque = new Bibliotheque(mediaInstance);
            TotalTime.Text = "00:00";
            ActualTime.Text = "00:00";
            progressSlider.AddHandler(Slider.PreviewMouseDownEvent, new MouseButtonEventHandler(progressSlider_MouseDown), true);
            playListBox.ItemsSource = playlist.mediaList;
            playListBox.MouseDoubleClick += new MouseButtonEventHandler(playSelected_Item);
            playListBox.SelectionMode = System.Windows.Controls.SelectionMode.Extended;
            this.KeyDown += new System.Windows.Input.KeyEventHandler(removeSelected_Item);
            bibliothequeBox.ItemsSource = bibliotheque.mediaList;
            bibliothequeBox.MouseDoubleClick += new MouseButtonEventHandler(bibliSelected_Item);
            bibliothequeBox.SelectionMode = System.Windows.Controls.SelectionMode.Extended;
        }
        private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            if (mediaElement.NaturalDuration.HasTimeSpan)
                progressSlider.Maximum = mediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
            else
            {
                TotalTime.Text = "00:00";
                ActualTime.Text = "00:00";
            }
        }
        private void playButton_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source == null)
            {
                play.IsChecked = false;
                return;
            }
            if (mediaElement.Clock != null)
            {
                if (mediaElement.Clock.IsPaused)
                    mediaElement.Clock.Controller.Resume();
                else
                    mediaElement.Clock.Controller.Pause();
            }
            else
            {
                play.IsChecked = true;
                playlist.playActual_Media();
                if (playlist.mediaList[playlist.currentMedia].type != 2)
                 mediaElement.Clock.CurrentTimeInvalidated += new EventHandler(Clock_CurrentTimeInvalidated);
            }
        }
        private void displayBibli_Click(object sender, RoutedEventArgs e)
        {
            if (bibliothequeBox.Visibility == Visibility.Visible)
            {
                menu_bibli.Visibility = Visibility.Hidden;
                bibliothequeBox.Visibility = Visibility.Hidden;
                menu_bibliothequeBox.Visibility = Visibility.Hidden;
                mediaElement.Visibility = Visibility.Visible;
            }
            else
            {
                menu_bibli.Visibility = Visibility.Visible;
                bibliothequeBox.Visibility = Visibility.Visible;
                menu_bibliothequeBox.Visibility = Visibility.Visible;
                mediaElement.Visibility = Visibility.Hidden;
            }
        }
        private void display_Playlist(object sender, RoutedEventArgs e)
        {
            if (playListBox.Visibility == Visibility.Visible)
            {
                mediaElement.Margin = new Thickness(0,72.267,0,75);
                bibliothequeBox.Margin = new Thickness(199.2,111.266,0,73.933);
                menu_bibliothequeBox.Margin = new Thickness(199.2, 72.267, 0, 0);
                playListBox.Visibility = Visibility.Hidden;
                menu_playList.Visibility = Visibility.Hidden;
            }
            else
            {
                menu_playList.Visibility = Visibility.Visible;
                mediaElement.Margin = new Thickness(0, 72.267, 210, 75);
                menu_bibliothequeBox.Margin = new Thickness(199.2, 72.267, 0, 73.933);
                bibliothequeBox.Margin = new Thickness(199.2, 111.266, 0, 73.933);
                playListBox.Visibility = Visibility.Visible;
            }
        }
        private void orderBy_Musique(object sender, RoutedEventArgs e)
        {
            if (ToggleButton_musiques.IsChecked == true)
            {

                bibliotheque.orderBy_Musique();
                ToggleButton_images.IsChecked = false;
                ToggleButton_vidéos.IsChecked = false;
            }
            else
            {
                bibliotheque.mediaList.Clear();
                bibliotheque.addMediaTo_List(bibliotheque.tmp);
            }
        }
        private void orderBy_Video(object sender, RoutedEventArgs e)
        {
            if (ToggleButton_vidéos.IsChecked == true)
            {
                bibliotheque.orderBy_Video();
                ToggleButton_musiques.IsChecked = false;
                ToggleButton_images.IsChecked = false;
            }
            else
            {
                bibliotheque.mediaList.Clear();
                bibliotheque.addMediaTo_List(bibliotheque.tmp);
            }
        }
        private void orderBy_Pics(object sender, RoutedEventArgs e)
        {
            if (ToggleButton_images.IsChecked == true)
            {
                bibliotheque.orderBy_Pics();
                ToggleButton_vidéos.IsChecked = false;
                ToggleButton_musiques.IsChecked = false;
            }
            else
            {
                bibliotheque.mediaList.Clear();
                bibliotheque.addMediaTo_List(bibliotheque.tmp);
            }
        }
        private void orderBy_Name(object sender, RoutedEventArgs e)
        {
            if (ToggleButton_titre.IsChecked == true)
            {
                bibliotheque.orderBy_AscendingName();
                ToggleButton_artiste.IsChecked = false;
                ToggleButton_durée.IsChecked = false;
                ToggleButton_genre.IsChecked = false;
            }
            else
              bibliotheque.orderBy_DescendingName();
        }
        private void orderBy_Artist(object sender, RoutedEventArgs e)
        {
            if (ToggleButton_artiste.IsChecked == true)
            {
                bibliotheque.orderBy_AscendingArtist();
                ToggleButton_durée.IsChecked = false;
                ToggleButton_genre.IsChecked = false;
                ToggleButton_titre.IsChecked = false;
            }
            else
                bibliotheque.orderBy_DescendingArtist();
        }
        private void orderBy_Duration(object sender, RoutedEventArgs e)
        {
            if (ToggleButton_durée.IsChecked == true)
            {
                bibliotheque.orderBy_AscendingDuration();
                ToggleButton_artiste.IsChecked = false;
                ToggleButton_genre.IsChecked = false;
                ToggleButton_titre.IsChecked = false;
            }
            else
                bibliotheque.orderBy_DescendingDuration();
        }
        private void orderBy_Type(object sender, RoutedEventArgs e)
        {
            if (ToggleButton_genre.IsChecked == true)
            {
                bibliotheque.orderBy_AscendingType();
                ToggleButton_artiste.IsChecked = false;
                ToggleButton_durée.IsChecked = false;
                ToggleButton_titre.IsChecked = false;
            }
            else
                bibliotheque.orderBy_DescendingType();
        }
        private void update_Click(object sender, RoutedEventArgs e)
        {
            bibliotheque.update();
        }
        private void drop_Media(object sender, System.Windows.DragEventArgs e)
        {
            StringCollection paths = ((System.Windows.DataObject)e.Data).GetFileDropList();

            if (playlist.mediaList.Count > 0)
                playlist.removeAll_Items();
            playlist.addMediaTo_List(paths.Cast<string>().ToArray<string>());
            if (playlist.mediaList.Count != 0)
            {
                playlist.playActual_Media();
                if (playlist.mediaList[playlist.currentMedia].type != 2)
                    mediaElement.Clock.CurrentTimeInvalidated += new EventHandler(Clock_CurrentTimeInvalidated);
                play.IsChecked = true;
            }
        }
        private void search_Media(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Media Files (*.avi, *.wmv, *.mp3, *.flv, *.jpg, *.png, *.mp4, *.mkv) | *.avi; *.wmv; *.mp3; *.flv; *.jpg; *.png; *.mp4; *.mkv";
            ofd.Multiselect = true;

            if (ofd.ShowDialog().ToString().Equals("OK"))
            {
                playlist.addMediaTo_List(ofd.FileNames);
                if (mediaElement.Source == null)
                {
                    playlist.playActual_Media();
                    if (mediaElement.Source != null)
                    {
                        if (playlist.mediaList[playlist.currentMedia].type != 2)
                         mediaElement.Clock.CurrentTimeInvalidated += new EventHandler(Clock_CurrentTimeInvalidated);
                        play.IsChecked = true;
                    }
                }
            }
        }
        private void nextMedia_Click(object sender, RoutedEventArgs e)
        {
            play.IsChecked = true;
            playlist.getNext_Media();
            if (playlist.mediaList[playlist.currentMedia].type != 2)
                mediaElement.Clock.CurrentTimeInvalidated += new EventHandler(Clock_CurrentTimeInvalidated);
        }
        private void previousMedia_Click(object sender, RoutedEventArgs e)
        {
            play.IsChecked = true;
            playlist.getPrevious_Media();
            if (playlist.mediaList[playlist.currentMedia].type != 2)
                mediaElement.Clock.CurrentTimeInvalidated += new EventHandler(Clock_CurrentTimeInvalidated);
        }
        private void savePlaylist_Click(object sender, RoutedEventArgs e)
        {
            playlist.saveActual_Playlist();
        }
        private void loadPlaylist_Click(object sender, RoutedEventArgs e)
        {
            playlist.load_Playlist();
            if (playlist.mediaList.Count > 0)
            {
                playlist.playActual_Media();
                play.IsChecked = true;
            }
        }
        private void stopButton_Click(object sender, RoutedEventArgs e)
        {
            if (mediaElement.Source == null)
                return;
            playlist.stopActual_Media();
            play.IsChecked = false;
        }
        private void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            progressSlider.Value = 0;
            playlist.getNext_Media();
        }
        private void progressSlider_MouseDown(object sender, MouseButtonEventArgs e)
        {
            isUserMovingSlider = true;
        }
        private void progressSlider_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (mediaElement.Clock != null)
            {
                TimeSpan m_offset = TimeSpan.FromMilliseconds(this.progressSlider.Value);
                mediaElement.Clock.Controller.Seek(m_offset, TimeSeekOrigin.BeginTime);
            }
            isUserMovingSlider = false;
        }
        private void bibliSelected_Item(object sender, MouseButtonEventArgs e)
        {
            int pos = bibliothequeBox.SelectedIndex;

            if (pos >= 0 && pos < bibliotheque.mediaList.Count)
            {
                playlist.addMediaTo_List(bibliotheque.mediaList);
                playlist.getSelected_Media(pos);
                if (playlist.mediaList[playlist.currentMedia].type != 2)
                  mediaElement.Clock.CurrentTimeInvalidated += new EventHandler(Clock_CurrentTimeInvalidated);
                play.IsChecked = true;
            }
        }
        private void Clock_CurrentTimeInvalidated(object sender, EventArgs e)
        {
            if (mediaElement.Clock == null || isUserMovingSlider)
                return;
            try
            {
                progressSlider.Value = mediaElement.Clock.CurrentTime.Value.TotalMilliseconds;
            }
            catch (Exception)
            {
                return;
            }
            TimeSpan t = mediaElement.Position;
            if (t.Hours > 0)
               ActualTime.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", t.Hours, t.Minutes, t.Seconds);
            else
               ActualTime.Text = string.Format("{0:D2}:{1:D2}", t.Minutes, t.Seconds);
            TotalTime.Text = playlist.mediaList[playlist.currentMedia].getTotal_Duration();
            if (playlist.mediaList[playlist.currentMedia].duration <= mediaElement.Clock.CurrentTime.Value.TotalSeconds + 1)
               mediaElement_MediaEnded(this, new RoutedEventArgs());
        }
        private void playSelected_Item(object sender, MouseButtonEventArgs e)
        {
            int pos = playListBox.SelectedIndex;

            if (pos >= 0 && pos < playlist.mediaList.Count)
            {
                playlist.getSelected_Media(pos);
                if (playlist.mediaList[playlist.currentMedia].type != 2)
                    mediaElement.Clock.CurrentTimeInvalidated += new EventHandler(Clock_CurrentTimeInvalidated);
                play.IsChecked = true;
            }
        }
        private void removeSelected_Item(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                List<int> indexes = new List<int>();

                foreach (object item in playListBox.SelectedItems)
                {
                    int index = playListBox.Items.IndexOf(item);
                    if (!indexes.Contains(index) && index >= 0)
                        indexes.Add(playListBox.Items.IndexOf(item));
                    if ((playlist.currentMedia) == index)
                    {
                        playlist.stopActual_Media();
                        play.IsChecked = false;
                    }
                }
                List<int> orderedIndexes = indexes.OrderByDescending(v => v).ToList();
                playlist.removeSelected_media(orderedIndexes);
            }
        }
    }
}
